// src/pages/home/home.js
import { billAPI, statisticsAPI } from '../../utils/api.js'
import { formatAmount, formatDate, getCurrentMonth, showError, showSuccess } from '../../utils/util.js'
import { userStorage, billStorage } from '../../utils/storage.js'

Page({
  data: {
    userInfo: null,
    currentMonth: '',
    monthlyStats: {
      totalIncome: 0,
      totalExpense: 0,
      balance: 0,
      billCount: 0
    },
    recentBills: [],
    budgetInfo: {
      budget: 0,
      spent: 0,
      remaining: 0,
      usageRate: 0
    },
    loading: true,
    refreshing: false
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.refreshData()
  },

  onPullDownRefresh() {
    this.refreshData(true)
  },

  onReachBottom() {
    // 加载更多账单
    this.loadMoreBills()
  },

  /**
   * 初始化页面
   */
  async initPage() {
    try {
      // 检查登录状态
      const userInfo = userStorage.getUserInfo()
      if (!userInfo) {
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return
      }

      this.setData({
        userInfo,
        currentMonth: getCurrentMonth()
      })

      await this.loadPageData()
    } catch (error) {
      console.error('页面初始化失败:', error)
      showError('页面加载失败')
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 加载页面数据
   */
  async loadPageData() {
    try {
      await Promise.all([
        this.loadMonthlyStats(),
        this.loadRecentBills(),
        this.loadBudgetInfo()
      ])
    } catch (error) {
      console.error('数据加载失败:', error)
    }
  },

  /**
   * 刷新数据
   */
  async refreshData(isPullRefresh = false) {
    if (isPullRefresh) {
      this.setData({ refreshing: true })
    }

    try {
      // 清除缓存
      billStorage.clearBillsCache()
      
      await this.loadPageData()
      
      if (isPullRefresh) {
        showSuccess('刷新成功')
      }
    } catch (error) {
      console.error('刷新失败:', error)
      showError('刷新失败')
    } finally {
      this.setData({ refreshing: false })
      if (isPullRefresh) {
        wx.stopPullDownRefresh()
      }
    }
  },

  /**
   * 加载月度统计
   */
  async loadMonthlyStats() {
    try {
      const currentMonth = this.data.currentMonth
      const [year, month] = currentMonth.split('-')
      const startDate = `${year}-${month}-01`
      const endDate = new Date(year, month, 0).toISOString().slice(0, 10)

      const result = await statisticsAPI.getStatistics({
        startDate,
        endDate,
        granularity: 'month'
      })

      if (result.success) {
        const stats = result.data.overview
        this.setData({
          monthlyStats: {
            totalIncome: stats.totalIncome || 0,
            totalExpense: stats.totalExpense || 0,
            balance: (stats.totalIncome || 0) - (stats.totalExpense || 0),
            billCount: stats.billCount || 0
          }
        })
      }
    } catch (error) {
      console.error('加载月度统计失败:', error)
    }
  },

  /**
   * 加载最近账单
   */
  async loadRecentBills() {
    try {
      const result = await billAPI.getBills({
        page: 1,
        limit: 10,
        sortBy: 'createTime',
        sortOrder: 'desc'
      })

      if (result.success) {
        this.setData({
          recentBills: result.data.bills || []
        })
      }
    } catch (error) {
      console.error('加载最近账单失败:', error)
    }
  },

  /**
   * 加载预算信息
   */
  async loadBudgetInfo() {
    try {
      // 这里应该调用预算API，暂时使用模拟数据
      const budgetInfo = {
        budget: 5000,
        spent: this.data.monthlyStats.totalExpense,
        remaining: 5000 - this.data.monthlyStats.totalExpense,
        usageRate: (this.data.monthlyStats.totalExpense / 5000) * 100
      }

      this.setData({ budgetInfo })
    } catch (error) {
      console.error('加载预算信息失败:', error)
    }
  },

  /**
   * 加载更多账单
   */
  async loadMoreBills() {
    // 实现分页加载逻辑
    console.log('加载更多账单')
  },

  /**
   * 快速记账 - 支出
   */
  onQuickExpense() {
    wx.navigateTo({
      url: '/src/pages/add/add?type=expense'
    })
  },

  /**
   * 快速记账 - 收入
   */
  onQuickIncome() {
    wx.navigateTo({
      url: '/src/pages/add/add?type=income'
    })
  },

  /**
   * 查看更多账单
   */
  onViewMoreBills() {
    wx.switchTab({
      url: '/src/pages/report/report'
    })
  },

  /**
   * 点击账单项
   */
  onBillTap(e) {
    const { bill } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/src/pages/bill-detail/bill-detail?id=${bill._id}`
    })
  },

  /**
   * 设置预算
   */
  onSetBudget() {
    wx.showModal({
      title: '设置月度预算',
      editable: true,
      placeholderText: '请输入预算金额',
      success: (res) => {
        if (res.confirm && res.content) {
          const amount = parseFloat(res.content)
          if (amount > 0) {
            this.setBudget(amount)
          } else {
            showError('请输入有效的预算金额')
          }
        }
      }
    })
  },

  /**
   * 设置预算
   */
  async setBudget(amount) {
    try {
      // 调用预算设置API
      showSuccess('预算设置成功')
      this.loadBudgetInfo()
    } catch (error) {
      console.error('设置预算失败:', error)
      showError('设置预算失败')
    }
  },

  /**
   * 查看预算详情
   */
  onViewBudget() {
    wx.navigateTo({
      url: '/src/pages/budget/budget'
    })
  },

  /**
   * 格式化金额显示
   */
  formatAmount(amount) {
    return formatAmount(amount)
  },

  /**
   * 格式化日期显示
   */
  formatDate(date) {
    return formatDate(date, 'MM-DD')
  },

  /**
   * 获取账单类型样式类
   */
  getBillTypeClass(type) {
    return type === 'income' ? 'amount-income' : 'amount-expense'
  },

  /**
   * 获取预算使用率颜色
   */
  getBudgetColor(usageRate) {
    if (usageRate >= 100) return '#ff4d4f'
    if (usageRate >= 80) return '#fa8c16'
    return '#52c41a'
  }
})